using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Btg.Zip { /// /// Windows File compression /// The SourceDirectory can be a directory or a file. Look at CopyHere in help for the Flags. /// This uses the Windows compression mechanism. Reference Microsoft Shell Controls and Automation on the Com tab. /// public class WindowsZipCompression { #region ZipFile /// /// zip up only the file name /// compress a file with L-Z algorithim /// /// file name in /// Out file name public void ZipFile(string Input, string Filename) { Shell32.Shell Shell = new Shell32.Shell(); //Create our Zip File CreateZipFile(Filename); //Copy the file or folder to it Shell.NameSpace(Filename).CopyHere(Input,0); //If you can write the code to wait for the code to finish, please let me know System.Threading.Thread.Sleep(2000); { } } /// /// /// pk zip header "PK" + (char)5 + (char)6; /// /// private void CreateZipFile(string filename) { //Create the header of the Zip File System.Text.ASCIIEncoding Encoder = new System.Text.ASCIIEncoding(); string sHeader = "PK" + (char)5 + (char)6; sHeader = sHeader.PadRight(22, (char)0); SaveFile(filename, sHeader); } /// /// actually saves the zip file /// /// /// private void SaveFile(string filename, string sHeader) { //Convert to byte array byte[] baHeader = System.Text.Encoding.ASCII.GetBytes(sHeader); //Save File - Make sure your file ends with .zip! FileStream fs = File.Create(filename); fs.Write(baHeader, 0, baHeader.Length); fs.Flush(); fs.Close(); fs = null; } #endregion ZipFile #region ZipDirectory /// /// zip up a whole directory /// pk zip header "PK\x05\x06" /// Example of InputDirectory - "C:\\Program Files" /// /// /// public void ZipDirectory(string InputDirectory, string Filename) { string ZipFile = Filename; System.IO.File.WriteAllText(ZipFile, "PK\x05\x06" + new String('\0', 18)); CopyDirectory(InputDirectory, ZipFile, 0); } /// /// /// /// /// /// private void CopyDirectory(string SourceDirectory, string DestinationDirectory, int Flags) { Shell32.Shell Sh = new Shell32.Shell(); Shell32.Folder SD = Sh.NameSpace(SourceDirectory); Shell32.Folder DD = Sh.NameSpace(DestinationDirectory); DD.CopyHere(SD, Flags); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Sh); } #endregion ZipDirectory } }